/*
 * File Name：ToucheFocusCameraPreview.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： ToucheFocusCameraPreview.java
 * Modify By：RES-KUNZHU
 * Modify Date：2013-5-7
 * Modify Type：Add
 */
package com.ciwong.mobilelib.widget;

import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.widget.CameraPreview.Callback;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;


/**
 * 触摸对焦相机
 *
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2013-5-7
 * @since ciwong v.1.0
 */
public class ToucheFocusCameraPreview extends FrameLayout implements
        SensorEventListener {

    private final int focusLength = 170;

    private final int focusLengthPer = 2;

    private final int delayMillis = 200;

    private final int offer = 10;

    private final int sensoreventValueposFirst = 0;

    private final int sensoreventValuePosSencond = 1;

    private final int sensoreventValuePosThrid = 2;

    private CameraPreview mCameraPreview;

    private ImageView mFocusIV;

    private Animation mFocusAnim;

    private float mLastX;

    private float mLastY;

    private float mLastZ;

    private boolean mAutoFacus;

    private SensorManager mSm;

    private Sensor mSensor;

    /**
     * 触摸对焦相机
     *
     * @param context  the context
     * @param attrs    the attribute set
     * @param defStyle the default style
     */
    public ToucheFocusCameraPreview(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    /**
     * 触摸对焦相机
     *
     * @param context the context
     * @param attrs   the attribute set
     */
    public ToucheFocusCameraPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * 触摸对焦相机
     *
     * @param context the context
     */
    public ToucheFocusCameraPreview(Context context) {
        super(context);
        init(context);
    }


    public CameraPreview getCameraPreview() {
        return mCameraPreview;
    }

    /**
     * 初始化
     */
    private void init(Context context) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        inflater.inflate(R.layout.touch_focus_camera, this);
        // 预览框
        mCameraPreview = (CameraPreview) findViewById(R.id.camera);

        // 焦点
        mFocusIV = (ImageView) findViewById(R.id.focus);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                focusLength, focusLength);
        mFocusIV.setLayoutParams(params);

        mFocusAnim = AnimationUtils.loadAnimation(getContext(),
                R.anim.focus_anim);
        mSm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        mCameraPreview.setVisibility(visibility);
    }

    /**
     * 预览监听
     *
     * @param mCallback 预览回调接口
     */
    public void setCreatedListener(Callback mCallback) {
        mCameraPreview.setCreatedListener(mCallback);
    }

    /**
     * 重新初始化
     */
    public void reInit() {
        mCameraPreview.reInit();
    }

    /**
     * 注册一个监听
     */
    public void registerListener() {
        mSm.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * 注销一个监听
     */
    public void unRegisterListener() {
        mSm.unregisterListener(this);
    }

    /**
     * Called when the accuracy of a sensor has changed.
     *
     * @param sensor   sensor
     * @param accuracy The new accuracy of this sensor
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[sensoreventValueposFirst];
        float y = event.values[sensoreventValuePosSencond];
        float z = event.values[sensoreventValuePosThrid];
        float deltaX = Math.abs(mLastX - x);
        float deltaY = Math.abs(mLastY - y);
        float deltaZ = Math.abs(mLastZ - z);

        if ((deltaX > offer || deltaY > offer || deltaZ > offer) && mAutoFacus) {
            mAutoFacus = false;
            if (CWCamera.instance() != null
                    && CWCamera.instance().getCamera() != null) {
                CWCamera.instance().getCamera().cancelAutoFocus();
            }
        }

        mLastX = x;
        mLastY = y;
        mLastZ = z;
    }

    @Override
    public boolean onTouchEvent(final MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            Camera camera = CWCamera.instance().getCamera();
            if (camera != null) {

                try {
                    // Camera.Parameters parameters = camera.getParameters();
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    int halfLength = focusLength / focusLengthPer;
                    if (x <= halfLength) {
                        x = halfLength;
                    }
                    if (y <= halfLength) {
                        y = halfLength;
                    }
                    if (x > getMeasuredWidth() - halfLength) {
                        x = getMeasuredWidth() - halfLength;
                    }
                    if (y > getMeasuredHeight() - halfLength) {
                        y = getMeasuredHeight() - halfLength;
                    }
                    // List<Area> list = new ArrayList<Camera.Area>();
                    // float x1 = (x / getMeasuredWidth()) * 2000 - 1000;
                    // float y1 = (y / getMeasuredHeight()) * 2000 - 1000;
                    // if (x1 < -980)
                    // {
                    // x1 = -980;
                    // }
                    // if (x1 > 980)
                    // {
                    // x1 = 980;
                    // }
                    // if (y1 < -980)
                    // {
                    // y1 = -980;
                    // }
                    // if (y1 > 980)
                    // {
                    // y1 = 980;
                    // }
                    // CWLog.d(TAG, "X:" + x1 + ";y:" + y1);
                    // Area a = new Area(new Rect((int) x1 - 20, (int) y1 - 20,
                    // (int) x1 + 20, (int) y1 + 20), 1000);
                    // list.add(a);
                    // parameters.setf
                    // camera.setParameters(parameters);
                    camera.autoFocus(new Camera.AutoFocusCallback() {

                        @Override
                        public void onAutoFocus(boolean success, Camera camera) {

                            // focusAnim.
                            // LayoutParams params =
                            // (LayoutParams)focus.getLayoutParams();
                            // params.width = (int)(focusLength * 0.7);
                            // params.height = (int)(focusLength * 0.7);
                            // focus.setLayoutParams(params);
                            if (success) {
                                mAutoFacus = true;
                                playMusic(true);
                                mFocusIV.setBackgroundResource(R.mipmap.duijiao1);

                            } else {
                                playMusic(false);
                                mFocusIV.setBackgroundResource(R.mipmap.duijiao1);
                            }

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mFocusIV.clearAnimation();
                                    mFocusIV.setVisibility(View.GONE);
                                }
                            }, delayMillis);
                        }
                    });

                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mFocusIV
                            .getLayoutParams();
                    params.height = focusLength;
                    params.width = focusLength;
                    params.leftMargin = x - halfLength;
                    params.topMargin = y - halfLength;
                    mFocusIV.setLayoutParams(params);
                    // focus.layout(x - halfLength, y-halfLength, x +
                    // halfLength, y + halfLength);
                    mFocusIV.setBackgroundResource(R.mipmap.duijiao1);
                    mFocusIV.setVisibility(View.VISIBLE);
                    mFocusIV.clearAnimation();
                    mFocusIV.startAnimation(mFocusAnim);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return true;
            }
        }
        return false;
    }

    /**
     * 播放音乐
     *
     * @param success 是否聚焦成功
     */
    private void playMusic(boolean success) {
        if (success) {
            AudioPlayer.getInstance().play(R.raw.focus_success, getContext(), null);
        } else {
            AudioPlayer.getInstance().play(R.raw.focus_failure, getContext(), null);
        }
    }

}
